package com.wsd.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.function.Function;

/**
  *    手写httpServer   第二步 优化封装
 * @author fengmoboy
 *
 */
public class Step2Server {
	
	/**
	 * socket服务
	 */
	public ServerSocket socketServer;
	
	/**
	 *	函数式编程 传入处理逻辑
	 */
	public Function<String, String> handler;
	
	public Step2Server(Function<String, String> handler) {
		this.handler = handler;
	}
	
	// Pending Queue
	public void listen(int port) throws IOException {
		socketServer = new ServerSocket(port);
		
		// Main Thread
		while(true) {
			this.accept();
		}
	}
	
	public void accept() {
		try {
			// Blocking...
			Socket socket = socketServer.accept();
			System.out.println("A socket created");
			
			DataInputStream iptStream = new DataInputStream(socket.getInputStream());
			BufferedReader bfReader = new BufferedReader(new InputStreamReader(iptStream));
			
			StringBuilder requestBuilder = new StringBuilder();
			
			String line = "";
			while(true) {
				line = bfReader.readLine();
				if(line == null || line.isEmpty()) {
					break;
				}
				requestBuilder.append(line+"\n");
			}
			String request = requestBuilder.toString();
			System.out.println(request);
			BufferedWriter bfWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			String response = this.handler.apply(request);
			//"HTTP/1.1 200 ok\n\nHello World!\n"
			bfWriter.write(response);
			bfWriter.flush();
			socket.close();
		} catch (SocketException se) {
			se.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) throws IOException {
		Step2Server step2Server = new Step2Server(req -> {
			return "HTTP/1.1 200 ok\n\nHello World!\n";
		});
		step2Server.listen(8000);
	}
}
